<template>
  <view class="safe-area-inset-bottom">
    <view class="swip_header">
      <swiperTabHead :tabBars="tabList" :tabIndex="tabIndex" @tabtap="handleTabtap"></swiperTabHead>
      <view class="bg_color">
        <uni-data-checkbox
            mode="button"
            v-model="queryParams.readed"
            :localdata="noticeReadOptions"
            @change="handleCheckbox"/>
      </view>
    </view>
    <!-- 任务消息 -->
    <view class="tabs cardList" style="margin-bottom: 100rpx;">
      <view v-if="!!dataList && dataList.length > 0">
        <checkbox-group @change="checkboxChange" style="display: inline-block;">
          <uni-card :is-shadow="false" v-for="(item,index) in dataList" :key="index" @click="detail(item)">
            <p style="padding: 10rpx 0;color: #8f8f94;font-size: 26rpx;" class="notice-content">{{ item.content }}</p>
            <view slot="actions" class="card-actions" style="justify-content: space-between;">
              <view @click.stop>
                <checkbox style="transform:scale(0.7)" color="#00a660" :value="item.id.toString()"
                          :checked="item.checked"/>
                <template v-for="(dictItem, index) in dicts.ec_notice_readed_status">
                  <template v-if="item.readed == dictItem.value">
                    <uni-tag :text="dictItem.text" size="small" :type="dictItem.type" style="margin-left: 20rpx;"/>
                  </template>
                </template>
              </view>
              <view style="font-size: 20rpx;">发布时间：{{ parseTimePage(item.createTime) }}</view>
              <view class="card-actions-item" @click.stop="handleDelete(item)">
                <text class="card-actions-item-text errorColor">删除</text>
              </view>
            </view>
          </uni-card>
        </checkbox-group>
        <!-- 加载更多 -->
        <uni-load-more color="#00a660" :status="loadStatus"/>
      </view>
      <!-- 暂无数据 -->
      <luanqingEmpty :show="true" text="没有更多数据啦" v-else/>
    </view>
    <!-- 底部全选/合并开票 -->
    <view class="foot-menu flex_between">
      <checkbox-group @change="checkboxAllChange">
        <label>
          <checkbox
              style="transform:scale(0.7)"
              color="#00a660"
              :checked="allFlag.checked"
              :value="allFlag.cb"/>
          全选
        </label>
      </checkbox-group>
      <view>
        <button size="mini" class="red_btn" :disabled="multiple" @click="handleDelete()">批量删除</button>
        <button size="mini" class="green_btn" style="margin-left: 10rpx;" :disabled="multiple" @click="handleReaded">
          批量已读
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import swiperTabHead from "@/components/slideTab/slideTab";
import luanqingEmpty from '@/components/luanqing-empty/luanqing-empty'
import {delSysNotice, listSysNotice} from "@/api/ec/person/notice/sysNotice"
import {delSysTaskNotice, listSysTaskNotice} from "@/api/ec/person/notice/sysTaskNotice"
import {getDictsByNameForUni} from "../../../../utils/dicts";
import {parseTime} from "../../../../utils/ruoyi";
import {readedTaskNotice} from "../../../../api/ec/person/notice/sysTaskNotice";
import {readedSysNotice} from "../../../../api/ec/person/notice/sysNotice";

export default {
  components: {luanqingEmpty, swiperTabHead},
  data() {
    return {
      // 数据字典
      dicts: {
        // 消息状态
        ec_notice_readed_status: [],
      },
      // tab标签
      tabList: [
        {title: '任务消息'},
        {title: '系统消息'}
      ],
      // 当前选中
      tabIndex: 0,
      // 消息否已读类型
      noticeReadOptions: [
        {text: '全部信息', value: 2},
        {text: '未读信息', value: 0},
        {text: '已读信息', value: 1}
      ],
      // 消息否已读类型选中
      noticeRead: 2,
      // 是否显示新成员未处理提示红点
      hiddenBadge: true,
      // 加载样式：more-加载前样式，loading-加载中样式，nomore-没有数据样式
      loadStatus: 'loading',
      // 数据列表
      dataList: [],
      //总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        readed: 2,
      },
      // 全选框
      allFlag: {
        value: 'cb',
        checked: false
      },
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
    }
  },
  onLoad() {
    this.getDicts()
    this.bindingRefreshData();
  },
  onUnload() {
    this.unbindingRefreshData();
  },
  created() {
    this.handleQuery();
  },
  /** 上拉刷新回调 */
  onReachBottom() {
    if (this.loadStatus != 'noMore' && this.total > this.dataList.length) {
      this.loadStatus = 'loading';
      // 延迟500毫秒显示loading效果
      setTimeout(() => {
        this.loadMore();
      }, 500)
    } else {
      // 停止加载
      this.loadStatus = 'noMore'
    }
  },
  methods: {
    // ===============================================================================================================
    // ==== 加载数据字典
    // ===============================================================================================================
    /**加载数据字典*/
    getDicts() {
      // 消息状态
      this.dicts.ec_notice_readed_status = getDictsByNameForUni("ec_notice_readed_status");
    },
    /** 绑定 */
    bindingRefreshData() {
      // 刷新页面数据
      uni.$on('refreshMessageIndex', () => {
        this.getNotReadedStatus();
        this.handleQuery();
      });
    },
    /** 解除绑定 */
    unbindingRefreshData() {
      uni.$off('refreshMessageIndex');
    },
    /** 日期格式化 */
    parseTimePage(createTime) {
      return parseTime(createTime, '{y}-{m}-{d} {h}:{i}:{s}');
    },
    /** 接受子组件传过来的值点击切换导航 */
    handleTabtap(index) {
      // 标记以选项
      this.tabIndex = index;
      // 标记全部消息
      this.queryParams.readed = 2;
      // 滚动到页面的目标位置
      uni.pageScrollTo({scrollTop: 0, duration: 300});
      // 查询数据列表
      this.handleQuery();
    },
    /** 只读已读类型切换 */
    handleCheckbox(e) {
      this.noticeRead = e.detail.value
      // 滚动到页面的目标位置
      uni.pageScrollTo({scrollTop: 0, duration: 300});
      // 查询数据列表
      this.handleQuery();
    },
    // ===============================================================================================================
    // ==== 复选框选择
    // ===============================================================================================================
    /** 全选复选框的checkbox-group  changge事件 */
    checkboxAllChange(e) {
      // 选中的选项数据
      let selection = [];
      // 取消全选
      if (e.detail.value.length == 0) {
        this.dataList.map(item => this.$set(item, 'checked', false));
        this.$set(this.allFlag, 'checked', false);
        selection = [];
      } else {
        // 全选
        this.dataList.map(item => {
          this.$set(item, 'checked', true);
          selection.push(item);
        });
        this.$set(this.allFlag, 'checked', true);
      }
      this.handleSelectionChange(selection);
    },
    /** 复选框组合的checkbox-group  changge事件*/
    checkboxChange(e) {
      let items = this.dataList;
      let values = e.detail.value;
      for (let i = 0, lenI = items.length; i < lenI; ++i) {
        const item = items[i];
        if (values.includes(item.id.toString())) {
          this.$set(item, 'checked', true);
        } else {
          this.$set(item, 'checked', false);
        }
      }
      // 是否全部勾选，判断全选与否状态
      let offCarArr = [];
      this.dataList.forEach(item => offCarArr.push(item));
      let allChecks = offCarArr.every(item => item.checked == true);
      allChecks ? this.$set(this.allFlag, 'checked', true) : this.$set(this.allFlag, 'checked', false);

      // 选中的选项数据
      let selection = [];
      this.dataList.forEach(item => (item.checked) ? selection.push(item) : '');
      this.handleSelectionChange(selection);
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    // ===============================================================================================================
    // ==== 数据列表
    // ===============================================================================================================
    /** 获取未读消息系统通知 */
    getNotReadedStatus() {
      // if (this.tabIndex == 0) {
      //   getNotTaskReaded().then(response => {
      //     if (response.data > 0) {
      //       this.hiddenBadge = false;
      //     } else {
      //       this.hiddenBadge = true;
      //     }
      //   });
      // } else {
      //   getNotSysReaded().then(response => {
      //     if (response.data > 0) {
      //       this.hiddenBadge = false;
      //     } else {
      //       this.hiddenBadge = true;
      //     }
      //   });
      // }
    },
    /** 搜索 */
    handleQuery() {
      if (this.tabIndex == 0) {
        this.getTaskList(true);
      } else {
        this.getSysList(true);
      }
    },
    /** 加载更多 */
    loadMore() {
      if (this.tabIndex == 0) {
        this.getTaskList(false);
      } else {
        this.getSysList(false);
      }
    },
    /**
     * 查询任务消息数据列表
     * @param reload true 重新加载数据； false 加载更多
     */
    getTaskList(reload) {
      if (reload) {
        this.queryParams.pageNum = 1;
        this.loadStatus = 'more'
        this.$modal.loading();
      }
      listSysTaskNotice(this.queryParams).then(response => {
        if (reload) {
          uni.hideLoading()
        }
        this.total = response.total;
        if (response.total > 0) {
          const dataRows = response.rows;
          this.dataList = reload ? dataRows : this.dataList.concat(dataRows);
        } else {
          this.dataList = [];
        }
        // 判断数据是否加载完全
        if (response.total <= this.dataList.length) {
          this.loadStatus = 'noMore'
        }
        // 页数+1
        this.queryParams.pageNum++
      }).catch(() => {
        if (reload) {
          uni.hideLoading()
        }
      });
    },
    /**
     * 查询系统消息数据列表
     * @param reload true 重新加载数据； false 加载更多
     */
    getSysList(reload) {
      if (reload) {
        this.queryParams.pageNum = 1;
        this.loadStatus = 'more'
        this.$modal.loading();
      }
      listSysNotice(this.queryParams).then(response => {
        if (reload) {
          uni.hideLoading()
        }
        this.total = response.total;
        if (response.total > 0) {
          const dataRows = response.rows;
          this.dataList = reload ? dataRows : this.dataList.concat(dataRows);
        } else {
          this.dataList = [];
        }
        // 判断数据是否加载完全
        if (response.total <= this.dataList.length) {
          this.loadStatus = 'noMore'
        }
        // 页数+1
        this.queryParams.pageNum++
      }).catch(() => {
        if (reload) {
          uni.hideLoading()
        }
      });
    },
    /** 删除任务信息 */
    handleDelete(item) {
      let that = this
      uni.showModal({
        title: '系统提示',
        confirmColor: '#00a660',
        content: '确认删除所选消息？',
        success: function (res) {
          if (res.confirm) {
            const ids = (!!item) ? item.id : that.ids;
            if (that.tabIndex == 0) {
              delSysTaskNotice(ids).then(() => {
                // this.getNotReadedStatus();
                that.handleQuery();
                that.$modal.msgSuccess("消息删除成功");
              });
            } else {
              delSysNotice(ids).then(() => {
                // this.getNotReadedStatus();
                that.handleQuery();
                that.$modal.msgSuccess("消息删除成功");
              });
            }
          }
        },
      })
    },
    /** 已读按钮操作 */
    handleReaded() {
      const ids = this.ids;
      if (this.tabIndex == 0) {
        readedTaskNotice(ids).then(() => {
          this.getNotReadedStatus();
          this.handleQuery();
          this.$modal.msgSuccess("消息已经标记为已读");
        });
      } else {
        readedSysNotice(ids).then(() => {
          this.getNotReadedStatus();
          this.handleQuery();
          this.$modal.msgSuccess("消息已经标记为已读");
        });
      }
    },
    /** 查看详情 */
    detail(item) {
      uni.navigateTo({url: './detail?dataDetails=' + JSON.stringify(item) + '&tabIndex=' + this.tabIndex});
    },
  }
}
</script>

<style lang="scss" scoped>
.flex_item {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

::v-deep .uni-data-checklist {
  flex: none !important;
}

.bg_color {
  padding: 14rpx 24rpx;
  background: #fff;
  display: flex;
}

.tabs {
  padding-top: calc(181rpx + constant(safe-area-inset-top));
  padding-top: calc(181rpx + env(safe-area-inset-top));
  padding-top: 181rpx;
}


.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 45px;
  border-top: 1px #eee solid;
}

.card-actions-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.notice-content {
  color: #777777;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  /* 显示行数 */
  -webkit-line-clamp: 2;
  display: -webkit-box;
  /*作为弹性伸缩盒子模型显示*/
  -webkit-box-orient: vertical;
  /*伸缩盒子的排列方式：从上到下垂直*/
}

.foot-menu {
  width: 100%;
  height: 100rpx;
  background: #fff;
  position: fixed;
  padding: 0 25rpx;
  bottom: 0; /**距离底部为0*/
  left: 0;
  z-index: 1;
  border-top: 2rpx #ebeef5 solid;
  display: flex;
}
</style>
